package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    @Override
    public Result<List<Category>> findAll() {
        List<Category> list = this.list();

        if (list.size() > 0){
            return new Result<>(200,true,"查询成功",list);
        }else {
            return new Result<>(404,false,"数据查询失败",list);
        }

    }

    @Override
    public Result<List<Category>> add(Category category) {
        //添加数据
        boolean saveCategory = this.save(category);
        if (saveCategory){
            //获取全部数据 返回给前台更新
            List<Category> data = findAll().getData();
            return new Result<>(200,true,"添加分类成功",data);
        }else {
            return new Result<>(404,false,"添加分类失败，数据已存在",null);
        }
    }

    @Override
    public Result<Object> findPage(Integer page, Integer size) {
        //构建分页查询对象
        IPage<Category> pageQuery = new Page<>(page, size);

        //查询分页
        this.page(pageQuery);

        //获取结果
        List<Category> records = pageQuery.getRecords();

        //获取数据条数
        long total = pageQuery.getTotal();
        //构建分页查询结果
        PageResult pageResult = new PageResult(total, records);

        if (total > 0){

            return new Result<>(200,true,"分页数据查询成功",pageResult);
        }else {
            return new Result<>(404,false,"分页数据查询失败,没有数据或者查询数据失败",pageResult);
        }
    }

    //按id查询用户
    @Override
    public Result<Object> findById(Integer id) {

        Category byId = this.getById(id);
        if (byId != null){
            return new Result<>(200,true,"查询指定用户成功",byId);
        }
            return new Result<>(404,false,"查询指定用户失败",null);
    }

    @Override
    public Result<Object> update(Category category) {
        //执行更新数据
        boolean updateResult = this.updateById(category);
        if (updateResult){
            return new Result<>(200,true,"更新数据成功",null);
        }
            return new Result<>(404,false,"更新数据失败",null);
    }

    @Override
    public Result<Object> delete(Integer id){
        boolean deleteResult = this.removeById(id);
        if (deleteResult){
            return new Result<>(200,true,"删除数据成功",null);
        }
        return new Result<>(404,false,"删除数据失败",null);
    }
}
